<template>
  <el-dialog title="消息提示" width="30%" :visible.sync="detModal" :close-on-click-modal="false">
    <p slot="header" style="text-align:center">
      <span>{{Message.messageTitle}}</span>
    </p>
    <div class="messageContent" v-html="Message.messageContent"></div>
    <div style="text-align:right;margin:10px 0;padding:0 60px;">{{Message.createTime}}</div>
  </el-dialog>
</template>
<script>
export default {
  data() {
    return {
      ws: {},
      readyState: 3, //默认连接关闭
      isShow: false,
      detModal: false,
      Message: {},
      userId: JSON.parse(sessionStorage.user).id,
    };
  },
  methods: {
    /**
     * 后台断开连接
     */
    disconnect(userId) {
      let params = {};
      params.userId = userId;
      this.$api.formPost("/api/mess/send/doDisconnect", params).then(res => {
        if (res.retHead.code == "0000000") {
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },

    openInfo() {
      const h = this.$createElement;
      const message = this.Message;

      const that = this;
      //打开消息提醒
      let myNotify = this.$notify({
        title: message.title,
        message: h(
          "i",
          {
            style: "color: teal",
            on: {
              click: () => {
                // 读取消息
                this.readMesssage(message.id);
                // 进入页面
                let path = message.path;
                if (path) {
                  let query = message.query;
                  that.jumpPath(path, query);
                }
                myNotify.close();
              }
            }
          },
          message.content
        )
      });
    },

    /**
     * 打开页面
     */
    jumpPath(path, query) {
      let currentUrl = location.href;
      if (currentUrl.endsWith(path)) {
        return;
      }
      let params = {};
      if (query) {
        params = JSON.parse(query);
      }
      this.$router.push({ path: path, query: params });
    },
    /**
     * 读取消息
     */
    readMesssage(id) {
      let params = {};
      params.id = id;
      this.$api.formPost("/api/mess/receive/doModById", params).then(res => {
        if (res.retHead.code == "0000000") {
        } else {
          this.$message.error(res.retHead.message);
        }
      });
    },

    updNoReadNum() {
      //更新未读消息
      this.$api
        .formPost("/api/mess/receive/doGetList", {
          readState: '0',
          receiveId: this.userId,
        })
        .then(res => {
          if (res.retHead.code == "0000000") {
            let total = res.retBody.total;
            const h = this.$createElement;
            this.$emit("getCount",total)
            let content = "一共有" + total + "条未读消息";
            const that = this;
            //打开消息提醒
            let myNotify = this.$notify({
              title: "历史未读消息提示",
              offset: 60,
              message: h(
                "i",
                {
                  style: "color: teal",

                  on: {
                    click: () => {
                      // 进入页面
                      let path = "/mess/receive";
                      let timestamp = new Date().getTime();
                      let query = { timestamp: timestamp };
                      that.jumpPath(path, JSON.stringify(query));
                      myNotify.close();
                    }
                  }
                },
                content
              )
            });
          } else {
            this.$message.error(res.retHead.message);
          }
        });
    },
    threadPoxi() {
      // 实际调用的方法(发送消息)
      //参数
      const agentData = "mymessage";
      //若是ws开启状态
      if (this.readyState === 1) {
        //  readyState   0 : 表示正在连接   1 :已连接 2 ：连接正在关闭 3 ：连接已经关闭或者连接不能打开。
        this.ws(agentData);
      }
      // 若是 正在开启状态，则等待300毫秒
      else if (this.readyState === 0) {
        let that = this; //保存当前对象this
        setTimeout(function() {
          that.websocketsend(agentData);
        }, 300);
      }
      // 若未开启 ，则等待500毫秒
      else {
        this.initWebSocket();
        let that = this; //保存当前对象this
        setTimeout(function() {
          that.websocketsend(agentData);
        }, 500);
      }
    },

    //初始化WebSocket
    initWebSocket() {
      const urlArr = this.baseURL.split(":");
      var domain = urlArr[1].substr(2);
      var userId = this.userId;
      if ("WebSocket" in window) {
        // var arr = process.env.ApiUrl.split(/\:/);
        var port = urlArr[2];
        this.ws = new WebSocket(
          "ws://" +
            domain +
            ":" +
            port +
            "/websocket/msgWebSocketServer?userId=" +
            userId +
            ""
        );
      } else if ("MozWebSocket" in window) {
        this.ws = new MozWebSocket(
          "ws://" +
            domain +
            "/websocket/msgWebSocketServer?userId=" +
            userId +
            ""
        );
      } else {
        this.ws = new SockJS(
          "http://" +
            domain +
            "/sockjs/websocket/msgWebSocketServer?userId=" +
            userId +
            ""
        );
      }
      this.ws.onopen = this.websocketopen;
      this.ws.onmessage = this.websocketonmessage;
      this.ws.onclose = this.websocketclose;
      this.ws.onerror = this.websocketerror;
    },

    websocketopen(e) {
      //打开
      if (this.ws.readyState) {
        //0 - 表示连接尚未建立。1 - 表示连接已建立，可以进行通信。2 - 表示连接正在进行关闭。3 - 表示连接已经关闭或者连接不能打开。
        console.log(
          "用户userId：" +
            this.userId +
            "连接成功,连接的ws地址：" +
            this.baseURL.split(":")[1].substr(2)
        );
      }
    },
    websocketonmessage(e) {
      //数据接收
      var obj = JSON.parse(e.data);
      // this.updNoReadNum(); //更新未读消息数
      this.Message = obj;
      this.openInfo();
    },
    websocketclose() {
      //关闭
      console.log("WebSocket已经关闭");
    },
    websocketerror() {
      //失败
      console.log("WebSocket连接失败");
    }
  },
  //页面刚进入时开启长连接
  created() {
    let top = document.documentElement.clientHeight - 100;
    this.initWebSocket();
    // this.$Notice.config({ top: top, duration: 3 });
    this.updNoReadNum();
  }
};
</script>

<style scoped>
.websocket {
  background: #fff;
  width: 200px;
  height: 200px;
  position: fixed;
  bottom: 0;
  right: 0;
  z-index: 9;
}
</style>
